home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 6111 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.8 KB

  1. Path: rcp6.elan.af.mil!rscernix!danpop
  2. From: danpop@mail.cern.ch (Dan Pop)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: hex to dec function?
  5. Date: 22 Feb 96 13:58:24 GMT
  6. Organization: CERN European Lab for Particle Physics
  7. Message-ID: <danpop.824997504@rscernix>
  8. References: <4gdh1b$bg@mailhost.mwmicro.com> <4gdolr$ha9@madeline.INS.CWRU.Edu> <4gg3h0INN59e@keats.ugrad.cs.ubc.ca>
  9. NNTP-Posting-Host: ues5.cern.ch
  10. X-Newsreader: NN version 6.5.0 #7 (NOV)
  11.  
  12. In <4gg3h0INN59e@keats.ugrad.cs.ubc.ca> c2a192@ugrad.cs.ubc.ca (Kazimir Kylheku) writes:
  13.  
  14. >In article <4gdolr$ha9@madeline.INS.CWRU.Edu>,
  15. >Michael A. Balfour <mab22@po.CWRU.Edu> wrote:
  16. > >
  17. > >In a previous article, aschlies@citynet.net () says:
  18. > >
  19. > >>Hi There,
  20. > >>
  21. > >>Is there a function that converts HEX to Dec in ANSI C?
  22. > >>
  23. > >You could try sscanf.  For example:
  24. > >
  25. > >main()
  26. > >{
  27. > >  char hex[9];
  28. > >  int dec;
  29. > >
  30. > >  strcpy(hex,"FFFF");
  31. >
  32. >Of course, someone will change the above to "         FFFFF", thus clobbering
  33. >your activation record, since you comitted the hex array to hold only 9
  34. >characters. 
  35. >
  36. >There is no reason why you can't use   char *hex = "FFFF";  in such a small
  37. >example.
  38.  
  39. For such a small example, sscanf("FFFF", "%x", &dec); would have done the
  40. job :-)
  41.  
  42. Note, however, that there are broken implementations where only the original
  43. example would work, while Kazimir's and mine would segfault!  This
  44. is because string literals _may_ be stored in read-only memory segments
  45. and some old sscanf implementations attempted to write back (actually
  46. to ungetc) the first character that couldn't be converted (the terminating
  47. null in this case).  A few years ago, somebody actually posted a similar
  48. example which crashed on his system and he couldn't understand why.
  49.  
  50. Dan
  51. --
  52. Dan Pop
  53. CERN, CN Division
  54. Email: danpop@mail.cern.ch 
  55. Mail:  CERN - PPE, Bat. 31 R-004, CH-1211 Geneve 23, Switzerland
  56.